import { Toast,Dialog } from "vant";
import moment from 'moment'
moment.locale('zh-cn')

export const checkMobile = phone =>{
    const myreg = /^[1][3,4,5,7,8,9][0-9]{9}$/;
    if (!myreg.test(phone)) {
        return false;
    } else {
        return true;
    }
}

export const toast = (message,position="top",duration=2000)=>{
    Toast({message,position,duration});
}

/**
 * 
 * @param {*} options 配置信息
 * @param {*} confirmCallback 确认回调
 * @param {*} cancelCallback 取消回调
 */
export const myJsDailog = (options,confirmCallback,cancelCallback)=>{
    let params = {
        title: 'Prompt Information',
        confirmButtonText:'Confirm',
        cancelButtonText:'Cancel',
        className:'myJsDailogBox'
    }
    Object.assign(params,options)
    Dialog.confirm(params).then(() => {
        confirmCallback && confirmCallback()
    }).catch(() => {
        cancelCallback && cancelCallback()
    });
}

export const loading = {
    open:(text,time)=>{
        Toast.loading({
            //overlay:true, //显示背景遮罩层
            message: 'Loading...',
            duration:0,
            className:'myLoading',
            icon: '/images/logo.jpeg',
        });      
    },
    close:()=>{
       Toast.clear()
    }
}

export const myOverlay ={
    open:()=>{
        const haswrap = document.querySelector('.myOverlay')
        if(haswrap){
            haswrap.style.display = 'block'
        }else{
            const wrap = document.createElement('div')
            wrap.className = 'myOverlay'
            wrap.style.position = 'fixed'
            wrap.style.zIndex = 100
            wrap.style.left = 0
            wrap.style.top = 0
            wrap.style.width = '100%'
            wrap.style.height = '100%'
            wrap.style.background = 'rgba(0, 0, 0, 0.01)'
            document.querySelector('body').appendChild(wrap)
        }
        
    },
    close:()=>{
        const wrap = document.querySelector('.myOverlay')
        if(wrap){
            wrap.style.display = 'none'
        }
    }
}

// moment--相关方法
export const mt = {
    curDateToymd:value=>{  // 获取当前日期
        if(!value) return ''
        return moment(value).format('YYYY-MM-DD')
    },
    // 格式化(如：2020-04-08T09:31:55.313Z)，返回日期
    timestampToDate:value=>{
        if(!value) return ''
        return moment(value).format('YYYY-MM-DD dddd')
    },
    // 时间戳转化为长时间时间
    timestampTodatetime1:value=>{
        if(!value) return ''
        return moment(value).format('YYYY-MM-DD HH:mm')
    },
    // 时间戳转化为长时间时间
    timestampTodatetime2:value=>{
        if(!value) return ''
        return moment(value).format('YYYY-MM-DD HH:mm:ss')
    },
    // 返回时分
    dateToms:value=>{
        if(!value) return ''
        return moment(value).format('HH:mm')
    },
    // 返回月日
    dateTomy:value=>{
        if(!value) return ''
        return moment(value).format("MMMDo")
    },
    //比较大小
    diff:(date1,date2=new Date(),type='minutes')=>{
        if(!date1) return ''
        const diff = moment(date1).diff(moment(date2), type)  
        return diff    ////diff>0时: date1>date2
    },
    dateFormat:(date)=>{
        if(!date) return ''
            const currentDate=new Date()  // 当前时间
            const tomorrow = moment().add(1, 'days').format('YYYY-MM-DD')  // 明天
            const afterTomorrow = moment().add(2, 'days').format('YYYY-MM-DD')  // 后天
            
            const diff = moment(date).diff(moment(currentDate), 'minutes')  //与当前时间比较， diff>0时: date>currentDate (单位为分钟) 

            const diff1 = moment(date).diff(moment(`${moment().format('YYYY-MM-DD')} 23:59:59`), 'minutes') // 与今天晚上12点比较
            const diff2 = moment(date).diff(moment(`${tomorrow} 23:59:59`), 'minutes') // 与明天晚上12点比较，
            const diff3 = moment(date).diff(moment(`${afterTomorrow} 23:59:59`), 'minutes')// 与后天晚上12点比较，
            //console.log(`diff:${diff},diff1:${diff1},diff2:${diff2},diff3:${diff3}`)
            if(diff>0 && diff1<=0){
                return `今天 ${moment(date).format('HH:mm')}`
            }else if(diff1>0 && diff2<=0){
                return `明天 ${moment(date).format('HH:mm')}`
            }else if(diff2>0 && diff3<=0){
                return `后天 ${moment(date).format('HH:mm')}`
            }else{
                return moment(date).format('MM-DD HH:mm')  // 直接返回日期格式化
            } 
    },
    addDate:(date,num,type='hours')=>{
        if(num>0){
            return moment(date).add(num, type).format('YYYY-MM-DD HH:mm:ss')
        }else if(num<0){
            return moment(date).subtract(Math.abs(num), type).format('YYYY-MM-DD HH:mm:ss')
        }else{
            return date
        }
    }
}

/**
 * H5调用原生app方法
 * @param {*} appFn APP提供的方法名称
 * @param {*} params 向appFn传递的参数（字符串形式）
 */
 export const H5CallAPPFuction = (appFn,params='')=>{
    let u = navigator.userAgent
    let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1 // android终端或者uc浏览器
    let isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
    if (isAndroid) {
        window.Android[appFn](params) 
    } else if (isiOS) {
        window.webkit.messageHandlers[appFn].postMessage(params)
    }else{
        alert("h5 to app error no terminal")
    }
}


export const base64toFile = (dataurl,filename='file') =>  {
    let arr = dataurl.split(',');
    let mime = arr[0].match(/:(.*?);/)[1];
    let suffix = mime.split('/')[1];
    let bstr = atob(arr[1]);
    let n = bstr.length;
    let u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], `${filename}.${suffix}`, {
       type: mime
    });
}

/**
 * 合并对象，只保留相同属性
 * @param {Object} target  目标对象
 * @param {Object} newObj  需要替换目标对象值的对象
 */
 export function mergeObject(target,newObj){
	for(let key in target){
		if(newObj[key]){
			target[key] = newObj[key]
		}	
	}
	return target
}

/**
 * 过滤掉对象属性值为空的属性
 * @param {*} target 
 * @returns 
 */
export function filterEmptyProp(target){
	for(let key in target){
		if(target[key]==0){

		}else if(!target[key]){ 
			delete target[key]  // 删除属性
		}	
	}
	return target
}

/**
 * 图片路径处理：跨域图片，转化为本地代理
 */
export const imgAgentUrl = (imgUrl)=>{
    if(!imgUrl){
        return
    }else if(imgUrl.indexOf('oss')>-1){
        return 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimage109.360doc.com%2FDownloadImg%2F2017%2F10%2F1116%2F113125087_31_20171011042226181.jpg&refer=http%3A%2F%2Fimage109.360doc.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1658557825&t=827ebb00faf4f95991aa2460f7aa1c81'
    }else if(imgUrl.indexOf('http:')>-1){
        return imgUrl.replace('http:','https:')
    }
    else{
        return imgUrl
    }
    
    // if(import.meta.env.ENV=='production'){ // 生产环境不做处理
    //     return imgUrl
    // }else{
    //     if(imgUrl.startsWith('http:') || imgUrl.startsWith('https:')){
    //         // 如果图片地址四完整路径，即带有域名(如：http://www.tst.metayuanjie.com/files/2022-06-22/5d0482d336d64c418c977999a7bdb32d.jpg)
    //         let urlStr = imgUrl.split('files') // 分割路径
    //         if(urlStr[1]){
    //             return `${import.meta.env.VITE_APP_BASE_API}/files${urlStr[1]}`
    //         }else{
    //             urlStr = imgUrl.split('mall-service')
    //             return `${import.meta.env.VITE_APP_BASE_API}/mall-service${urlStr[1]}`
    //         }
            
    //     }
    // }
    
}

/**
 * 监听touch事件，获取滑动的方向
 * @param {*} callback 
 */
export const monitorTouch = callback=>{
    const mybody = document.getElementsByTagName('body')[0]
    let startX, startY, moveEndX, moveEndY, X, Y
    mybody.addEventListener('touchstart', function(e) {
        e.preventDefault();
        startX = e.touches[0].pageX;
        startY = e.touches[0].pageY;
    });
    mybody.addEventListener('touchmove', function(e) {
        e.preventDefault();
        moveEndX = e.changedTouches[0].pageX;
        moveEndY = e.changedTouches[0].pageY;
        X = moveEndX - startX;
        Y = moveEndY - startY;
        if ( X > 0 ) {callback('right',X)}
        else if ( X < 0 ) {callback('left',X)}
        else if ( Y > 0) {callback('bottom',Y)}
        else if ( Y < 0 ) {callback('top',Y)}
        else{callback()}
    });
}

